package com.Adapters.Items;


import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;
import com.Animations.AnimUtil;
import com.Animations.AnimUtil.AnimationCompleted;
import com.Animations.AnimationLists;
import com.Data.Albums;
import com.Data.Albums.onUpdateCompleted;
import com.Data.Post;
import com.Data.Post.onDeletePictureCompleted;
import com.Data.Post.onUploadPictureCompleted;
import com.Data.User;
import com.Dialogs.DialogPicture;
import com.Downloaders.ProfilePictureDownloader;
import com.Downloaders.ProfilePictureDownloader.onProfilePictureDownloaded;
import com.Init.ImageDownloaderInit;
import com.Listeners.PostItemsListeners.CommentClickListener;
import com.Listeners.PostItemsListeners.ImagePostClickListener;
import com.Listeners.PostItemsListeners.LikeClickListener;
import com.Listeners.PostItemsListeners.LikeCompleted;
import com.Listeners.PostItemsListeners.LocationClickListener;
import com.Listeners.PostItemsListeners.ProfileClickListener;
import com.Listeners.PostItemsListeners.TagClickListener;
import com.Managers.DirManagerClass;
import com.Managers.FragmentManagerClass;
import com.Managers.PictureIntentManagerClass;
import com.Managers.PictureManagerClass;
import com.Managers.UserManagerClass;
import com.TextFormat.UtilFonts;
import com.UtilDate.UtilDate;
import com.activities.DefaultFunctions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.ImageLoadingProgressListener;
import com.shareup.R;


public class ItemPostPicture implements ItemPost {

    private ImageLoader imgLoader;

    private Context context;

    private ViewHolder holder;

    private final LayoutInflater inflater;

    private final User Logged;

    private DefaultFunctions main;

    private final Post picture;

    // /////////////////////////////////////////////////
    // CLASS TO SHOW PICTURE OPTIONS
    // ///////////////////////////////////////////////
    class DialogClickListener implements OnClickListener {

        @Override
        public void onClick(View v) {

            {
                createDialogPicture();
            }
        }
    }

    class ViewHolder {

        public ImageView action;

        public TextView comment;

        public ImageView comment_button;

        public TextView comments_count;

        public TextView date;

        public TextView locationText;

        public ToggleButton like_button;

        public TextView likes_count;

        public ImageView location_button;

        public TextView name;

        public ImageView post;

        public ImageView profile;

        public ProgressBar progress;

        public ImageView tag_button;

        public TextView tags_count;

        public RelativeLayout containerPicture;

    }

    public ItemPostPicture(LayoutInflater inflater, Post picture,
                DefaultFunctions main, ImageLoader loader) {

        super();

        this.inflater = inflater;
        this.picture = picture;
        this.context = main.getParentActivity();
        this.main = main;
        this.Logged = UserManagerClass.UserLogged;
        this.imgLoader = loader;

    }

    /*
     * Show the animation of PostIn in AnimationUtil
     * @see com.Adapters.Items.ItemPost#AnimateIn()
     */
    @Override
    public void AnimateIn() {

        AnimUtil.PostIn(holder.post.getContext(), holder.post, new AnimationCompleted() {

            @Override
            public void Completed() {

                holder.post.setVisibility(View.VISIBLE);

            }
        });

    }

    /*
     * Show the animation of PostOut in AnimationUtil
     * @see com.Adapters.Items.ItemPost#AnimateOut()
     */
    @Override
    public void AnimateOut(AnimationCompleted callback) {

        AnimUtil.PostOut(holder.post.getContext(), holder.post, callback);

    }

    /*
     * (non-Javadoc)
     * @see com.Adapters.Items.ItemPost#clearAnimatonList()
     */
    @Override
    public void clearAnimatonList() {

        AnimationLists.displayedImages.clear();

    }

    /*
     * (non-Javadoc)
     * @see com.Adapters.Items.ItemPost#delete()
     */
    @Override
    public void delete() {

        AlertDialog.Builder dg = new AlertDialog.Builder(context);
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflater.inflate(R.layout.dialog_actions, null);
        TextView message = (TextView) v.findViewById(R.id.message_dialog);
        UtilFonts.setTextRegularFont(message);
        Button accept = (Button) v.findViewById(R.id.dialog_action_a_button);
        UtilFonts.setTextRegularFont(accept);
        Button cancel = (Button) v.findViewById(R.id.dialog_action_c_button);
        UtilFonts.setTextRegularFont(cancel);
        //
        message.setText(R.string.dialog_question_delete_picture_message);
        //
        dg.setView(v);
        //
        final AlertDialog alert = dg.create();
        accept.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                removeAt();

                alert.cancel();
            }
        });
        cancel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                alert.cancel();
            }
        });
        //
        //
        //
        alert.show();

    }

    public void display(ImageView image, String url, final ProgressBar progressbar) {

        imgLoader.displayImage(url, image, ImageDownloaderInit.getOptionsForList(), new ImageLoadingListener() {

            @Override
            public void onLoadingCancelled(String imageUri, View view) {

            }

            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {

                progressbar.setVisibility(View.GONE);

                if (loadedImage != null) {
                    ImageView postImage = (ImageView) view;
                    boolean firstDisplay = !AnimationLists.displayedImages.contains(imageUri);
                    if (firstDisplay) {
                        AnimateIn();
                        postImage.setVisibility(View.VISIBLE);
                        AnimationLists.displayedImages.add(imageUri);
                    }

                }
            }

            @Override
            public void onLoadingFailed(String imageUri, View view, FailReason failReason) {

                progressbar.setVisibility(View.GONE);

            }

            @Override
            public void onLoadingStarted(String imageUri, View view) {

            }

        }, new ImageLoadingProgressListener() {

            @Override
            public void onProgressUpdate(String imageUri, View view, int current, int total) {

                progressbar.setVisibility(View.VISIBLE);
                progressbar.setMax(total);
                progressbar.setProgress(current);

            }
        });

    }

    @Override
    public int getCommentsCount() {

        return picture.getPictureCounters().getCommentsCount();
    }

    @Override
    public int getLikesCount() {

        return picture.getPictureCounters().getLikesCount();
    }

    public Post getPicture() {

        return this.picture;
    }

    // /////////////////////////////////////////////////
    // CLASS TO SHOW PICTURE IN GALLERY
    // ///////////////////////////////////////////////

    @Override
    public int getPostId() {

        return picture.getID();
    }

    @Override
    public String getPublicationDate() {

        return picture.getPublicationDate();
    }

    // /////////////////////////////////////////////////
    // CLASS TO HANDLE COMMENT CLICK
    // ///////////////////////////////////////////////
    int position = 0;

    @Override
    public View getView(View convertView, int position) {

        this.position = position;
        View view = null;

        if (convertView == null) {
            int resource = R.layout.item_post_picture;

            ViewGroup viewGroup = (ViewGroup) inflater.inflate(resource, null);
            holder = new ViewHolder();

            setTextsLayout(viewGroup);

            viewGroup.setTag(holder);
            view = viewGroup;

        }
        else {
            holder = (ViewHolder) convertView.getTag();
            view = convertView;
        }
        if (holder.post.getTag() != picture.getPathFull()) {
            holder.post.setImageDrawable(null);
            PictureManagerClass.scalePostImage(picture.getWidth(), picture.getHeight(), holder.post);

        }
        holder.post.setTag(picture.getPathFull());

        setTexts(position);

        return view;
    }

    @Override
    public int getViewType() {

        return RowType.PICTURE_POST.ordinal();
    }

    @Override
    public void setCommentsCount(int count) {

        picture.getPictureCounters().setCommentsCount(count);

    }

    public void setCurrentAsCover() {

        Uri picname = DirManagerClass.getPathFromPicture(picture.getPathFull());
        PictureIntentManagerClass.uploadPicture(FragmentManagerClass.aMain, false, true, picname, new onUploadPictureCompleted() {

            @Override
            public void Completed(String result) {

                String[] res = result.split("#");
                UserManagerClass.UserLogged.setCoverPicture(res[0]);
                new UserManagerClass(FragmentManagerClass.aMain).saveInfo(UserManagerClass.UserLogged);

            }
        });
    }

    public void setCurrentAsAlbumCover() {

        Albums als = new Albums(Albums.ACTION_UPDATE_COVER);
        als.setContext(context);
        als.setID(picture.getAlbum().getID());
        als.setCover(String.valueOf(picture.getID()));
        als.setCallbackUpdate(new onUpdateCompleted() {

            @Override
            public void Completed(String result) {

                picture.getAlbum().setCover(picture.getPathThumb());;
                Albums al = FragmentManagerClass.aAlbumDetail.album;

                al.setCover(picture.getPathThumb());
                FragmentManagerClass.aAlbum.setAlbum(al);

            }
        });
        als.execute();

    }

    public void setCurrentAsProfile() {

        Uri picname = DirManagerClass.getPathFromPicture(picture.getPathFull());
        PictureIntentManagerClass.performCrop(FragmentManagerClass.aMain, picname);
    }

    @Override
    public void setLikesCount(int count) {

        picture.getPictureCounters().setLikesCount(count);

    }

    public void setOwnerShip() {

        int idOwner = picture.getUser().getID();
        int idLogger = Logged.getID();

        if (holder != null && holder.action != null) {
            if (idOwner == idLogger) {
                if (holder.action.getVisibility() == View.GONE)
                    holder.action.setVisibility(View.VISIBLE);
            }
            else {
                if (picture.getPermission() == 0)
                    holder.action.setVisibility(View.GONE);
                else
                    holder.action.setVisibility(View.VISIBLE);

            }
        }

    }

    public void updatePermissions() {

    }

    @Override
    public void updatePublicationDate(String newDate) {

        picture.setPublicationDate(newDate);
        setTimeDiff();
    }

    private void createDialogPicture() {

        boolean isOwner = picture.getUser().getID() == UserManagerClass.UserLogged.getID();
        DialogPicture dl = new DialogPicture(context, isOwner, this);
        dl.setTitle(Logged.getRealName());
        dl.show();
    }

    private void downloadImagePost() {

        if (!picture.getPathFull().equals("null")) {
            if (holder.containerPicture.getVisibility() == View.GONE)
                holder.containerPicture.setVisibility(View.VISIBLE);

            display(holder.post, picture.getPathFull(), holder.progress);
        }

        else
            holder.containerPicture.setVisibility(View.GONE);

    }

    private void downloadImageProfile() {

        ProfilePictureDownloader pd = new ProfilePictureDownloader();
        pd.setCallbackProfilePicture(new onProfilePictureDownloaded() {

            @Override
            public void completed(Bitmap result) {

                holder.profile.setImageBitmap(result);
                downloadImagePost();

            }
        });
        pd.execute(picture.getUser().getProfilePicture());
    }

    private String getTagsCount() {

        String tres = picture.getTags().trim();
        if (!tres.equals("")) {
            String[] tresp = tres.split(",");
            int total = tresp.length;
            if (tres.length() > 0 && tres.charAt(0) == ',')
                total--;
            tres = "" + total;
        }
        else {
            tres = "0";
        }
        //
        return tres;
    }

    private void removeAt() {

        Post pic = new Post(Post.ACTION_DELETE, context, null);
        pic.setID(picture.getID());
        pic.setUser(new User());
        pic.getUser().setID(Logged.getID());
        pic.setCallbackDeletePicture(new onDeletePictureCompleted() {

            @Override
            public void Completed(String result) {

                AnimUtil.PostOut(context, holder.post, new AnimationCompleted() {

                    @Override
                    public void Completed() {

                        DirManagerClass.deleteCachedPicture(picture.getPathFull());
                        main.remove(picture);
                        AnimateIn();

                    }
                });

            }
        });
        pic.execute();

    }

    private void setCounters() {

        String cres = ""
                    + picture.getPictureCounters().getCommentsCount();
        String lres = ""
                    + picture.getPictureCounters().getLikesCount();
        //
        holder.likes_count.setText(lres);
        holder.comments_count.setText(cres);
        holder.tags_count.setText(getTagsCount());
        //
        setOwnerShip();
        // START IMAGE DOWNLOAD AFTER ITS SETTLED UP
        downloadImageProfile();

    }

    private void setImagesLayout(View itemView) {

        holder.profile = (ImageView) itemView.findViewById(R.id.user_image_profile);
        //
        holder.post = (ImageView) itemView.findViewById(R.id.post_imagen_post);
        //
        holder.action = (ImageView) itemView.findViewById(R.id.post_button_action);
        //
        holder.comment_button = (ImageView) itemView.findViewById(R.id.post_button_comment);
        //
        holder.like_button = (ToggleButton) itemView.findViewById(R.id.post_button_like);
        //
        holder.tag_button = (ImageView) itemView.findViewById(R.id.post_button_tag);
        //
        holder.location_button = (ImageView) itemView.findViewById(R.id.post_button_location);
        //
        holder.progress = (ProgressBar) itemView.findViewById(R.id.post_progress);
        //
        holder.containerPicture = (RelativeLayout) itemView.findViewById(R.id.post_image_container);

    }

    private void setTexts(int position) {

        holder.action.setOnClickListener(new DialogClickListener());
        // SETS THE DIFFERENCE OF TIME
        setTimeDiff();

        holder.like_button.setOnClickListener(new LikeClickListener(picture, new LikeCompleted() {

            @Override
            public void Completed() {

                setCounters();

            }
        }));
        holder.comment_button.setOnClickListener(new CommentClickListener(picture));
        holder.tag_button.setOnClickListener(new TagClickListener(picture));
        holder.post.setOnClickListener(new ImagePostClickListener(picture.getPathFull(), position));

        //
        if (picture.getGeoTag().getLatitude() != 0
                    && picture.getGeoTag().getLongitude() != 0) {
            holder.location_button.setVisibility(View.VISIBLE);
            holder.locationText.setVisibility(View.VISIBLE);
            holder.location_button.setOnClickListener(new LocationClickListener(picture, RowType.PICTURE_POST));
            holder.locationText.setOnClickListener(new LocationClickListener(picture, RowType.PICTURE_POST));
            holder.locationText.setText(picture.getGeoTag().toString());
        }
        else {
            holder.locationText.setVisibility(View.GONE);
            holder.location_button.setVisibility(View.GONE);
        }
        //
        holder.like_button.setChecked(false);
        //
        if (picture.getPictureCounters() != null
                    && picture.getPictureCounters().getIsMine() > 0) {
            holder.like_button.setChecked(true);
        }

        holder.comment.setText(picture.getComment());
        holder.name.setText(picture.getUser().getRealName());
        holder.name.setOnClickListener(new ProfileClickListener(picture, main.getParentActivity()));
        holder.profile.setOnClickListener(new ProfileClickListener(picture, main.getParentActivity()));

        setCounters();
    }

    private void setTextsLayout(View itemView) {

        holder.comment = (TextView) itemView.findViewById(R.id.user_comment);
        holder.name = (TextView) itemView.findViewById(R.id.user_name);
        holder.date = (TextView) itemView.findViewById(R.id.user_date);
        //
        holder.likes_count = (TextView) itemView.findViewById(R.id.post_text_likes_count);
        holder.comments_count = (TextView) itemView.findViewById(R.id.post_text_comments_count);
        //
        holder.tags_count = (TextView) itemView.findViewById(R.id.post_tags_counter);
        holder.locationText = (TextView) itemView.findViewById(R.id.location_text);
        UtilFonts.setTextRegularFont(holder.locationText, holder.comment, holder.comments_count, holder.tags_count, holder.likes_count);
        UtilFonts.setTextBoldFont(holder.name);
        UtilFonts.setTextBoldFont(holder.date);

        // CALL TO SET IMAGE VIEWS

        setImagesLayout(itemView);
    }

    private void setTimeDiff() {

        UtilDate dt = new UtilDate(holder.date.getContext());
        dt.setTimeDifference(picture.getPublicationDate(), holder.date);
    }

    /*
     * (non-Javadoc)
     * @see com.Adapters.Items.ItemPost#getPosition()
     */
    @Override
    public int getPosition() {

        return position;
    }

}
